package com.maixin.code.service;

import java.io.File;
import java.util.List;

import com.maixin.code.dao.DAO;
import com.maixin.code.entity.UserWorkTimeInfo;
import com.maixin.code.utils.CommonValues;
import com.maixin.code.utils.DateUtils;
import com.maixin.code.utils.ExcelUtils;

public class UserWorkTimeInfoService {
	private DAO<UserWorkTimeInfo> baseDao;
	
	
	/**
	 * 根据上传的Excel将数据保存到数据库中
	 * @param uploadFile
	 * @return
	 */
	public void saveExcelWorkTime(File uploadFile) {
		try {
			List<List<UserWorkTimeInfo>> list = ExcelUtils
					.loadExcelWorkTime(uploadFile);
			if (null != list && list.size() != 0) {
				for (int i = 0; i < list.size(); i++) {
					List<UserWorkTimeInfo> worktimeList = list.get(i);
					UserWorkTimeInfo workTimeObject = worktimeList.get(0);
					String times = "";
					for (int j = 0; j < worktimeList.size(); j++) {
						UserWorkTimeInfo info = worktimeList.get(j);
						times += info.getWorkTimePm() + ",";
					}
					workTimeObject = checkWorkTime(times, workTimeObject);
					this.getBaseDao().save(workTimeObject);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 分析excel的数据
	 * @param times
	 * @param workTimeObject
	 * @return
	 */
	private UserWorkTimeInfo checkWorkTime(String times,UserWorkTimeInfo workTimeObject) {
		String [] arr1 = times.split(",");
		String time = arr1[0].split(" ")[0];	//获得日期
		if(arr1.length >= 4){
			//可直接比较
			int am1 = DateUtils.compareDate(arr1[0], time+CommonValues.STANDARDTIME[0]);
			int am2 = DateUtils.compareDate(arr1[1], time+CommonValues.STANDARDTIME[1]);
			int pm1 = DateUtils.compareDate(arr1[arr1.length-2], time+CommonValues.STANDARDTIME[2]);
			int pm2 = DateUtils.compareDate(arr1[arr1.length-1], time+CommonValues.STANDARDTIME[3]);
			if(am1>0||pm1>0){
				//上午迟到或下午迟到
				workTimeObject.setWorktimeState(CommonValues.WORKTIMETYPE[0]);
			}
			if(am2<0||pm2<0){
				//上午早退或下午早退
				workTimeObject.setWorktimeState(CommonValues.WORKTIMETYPE[1]);
			}
			workTimeObject.setWorkTimeAm(arr1[0]+"  -  "+arr1[1]);
			workTimeObject.setWorkTimePm(arr1[arr1.length-2]+"  -  "+arr1[arr1.length-1]);
			
		}else{
			//不比较,直接显示数据,并提示数据错误
			if(arr1.length ==3){
				workTimeObject.setWorkTimeAm(arr1[0]+"  -  "+arr1[1]);
				workTimeObject.setWorkTimePm(arr1[2]+"  -  ");
			}else if(arr1.length ==2){
				workTimeObject.setWorkTimeAm(arr1[0]+"  -  "+arr1[1]);
			}else{
				workTimeObject.setWorkTimeAm(arr1[0]+"  -  ");
			}
			//打卡异常
			workTimeObject.setWorktimeState(CommonValues.WORKTIMETYPE[2]);
		}
		return workTimeObject;
	}
	
	
	
	public DAO<UserWorkTimeInfo> getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(DAO<UserWorkTimeInfo> baseDao) {
		this.baseDao = baseDao;
	}
}
